package com.centanet.framework.utils;

import com.centanet.framework.interfaces.IProgressRequestListener;
import com.centanet.framework.interfaces.IProgressResponseListener;
import com.centanet.framework.network.ProgressRequestBody;
import com.centanet.framework.network.ProgressResponseBody;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;

/**
 * 进度帮助类
 */
public final class ProgressHelper {

    private ProgressHelper() {
        // Utility class.
    }

    /**
     * 响应进度
     *
     * @param okHttpClient              okHttpClient
     * @param IProgressResponseListener 响应进度
     * @return okHttpClient
     */
    public static OkHttpClient addProgressResponseListener(OkHttpClient okHttpClient, final IProgressResponseListener IProgressResponseListener) {
        OkHttpClient clone = okHttpClient.clone();
        clone.networkInterceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                //拦截
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), IProgressResponseListener))
                        .build();
            }
        });
        return clone;
    }

    /**
     * 上传回调
     *
     * @param requestBody              请求
     * @param IProgressRequestListener 请求进度
     * @return ProgressRequestBody
     */
    public static ProgressRequestBody addProgressRequestListener(RequestBody requestBody, IProgressRequestListener IProgressRequestListener) {
        return new ProgressRequestBody(requestBody, IProgressRequestListener);
    }
}
